package service

import (
	"context"
	"fx_swift_schedule/internal/model"
	"fx_swift_schedule/pkg/code"
	"fx_swift_schedule/pkg/global"
	"fx_swift_schedule/pkg/internalerrors"
	"fx_swift_schedule/pkg/logger"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-module/carbon/v2"
)

type ISchedulerSrv interface {
	AutoAdaptManagementFee(ctx context.Context) error
}
type schedulerSrv struct {
}

func NewSchedulerSrv() ISchedulerSrv {
	return &schedulerSrv{}
}

// 定时任务自动变更管理费
func (s *schedulerSrv) AutoAdaptManagementFee(ctx context.Context) error {
	logger.SugarLogger.Info("定时任务自动变更管理费开始执行...................")
	var (
		err            error
		managementList []*model.FxAgentManagement
	)
	if err = global.GFDB.Ctx(ctx).Schema("card").Model("fx_agent_management").
		Where("future_effective_date <> '' and future_management_fee IS NOT NULL").Scan(&managementList); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, "数据查询异常")
	}
	if len(managementList) > 0 {
		for _, valueObj := range managementList {
			if carbon.Parse(carbon.Now().ToDateString()).Eq(carbon.Parse(valueObj.FutureEffectiveDate)) {
				if _, err = global.GFDB.Schema("card").Model("fx_agent_management").
					Data(g.Map{"future_effective_date": "", "future_management_fee": 0,
						"effective_date": valueObj.FutureEffectiveDate, "management_fee": valueObj.FutureManagementFee}).
					Where("account=?", valueObj.Account).Update(); err != nil {
					logger.SugarLogger.Error(err)
					return internalerrors.New(code.ErrUnknown, "更新有效期报错")
				}
			}
		}
	}
	return err
}
